package pkg.drowne.org;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.PowerManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.TextView;

public class locate extends MapActivity implements OnClickListener, OnLongClickListener {
	
    private boolean pollingstart=false;
    
	// Preference file
    public static final String PREF_FILE = "pf2";
    private SharedPreferences preferences;

	// General Activity
    private MapView mapView;
    private boolean refreshing = false;
	   
	// General Game  
    private boolean host = false;
    private boolean centerIsSet = false;
    
    // Player State
    private int playerState = -1;
    private boolean enterPlayerState = true;
    private boolean exitPlayerState = false;
    private int oldPlayerState;
    private int playerTeam;
    
    // Score and timer
    int matchScore;
    int matchTime;
    
    // Power counters
    private int radarTimer = 0;
    private int jammerTimer = 0;
    
    // Capture state
    private int captureState = -1;
    private int captureTimer = 0;
    private int oldCaptureState = -1;
    
    // Player State Thread Timer
    TimerTask refreshPlayerStateTask;
	final Handler handlerPlayerState = new Handler();
	Timer tPlayerState = new Timer();
    
	// Game Session
    private int gameSessionID = 0;
    private int idgame = 0;	
	
	// Location
	private static final int NEWER_CHECK = 1000 * 2;
	private GeoPoint point;
    private Location bestLocation;
    private LocationManager locationManager;
    private LocationListener locationListener;
    private Double latDoubleValue = (double) 0, lonDoubleValue = (double) 0;
    private Double myLat = (double) 0, myLon = (double) 0;
	
	// Overlays
	private List<Overlay> mapOverlays;
	private List<Overlay> mapOverlaysAllays;
	private Drawable posmarker;
	private OverlayItem playerOverlayItem;
	private OverlayManager itemizedoverlay;
	
    // Radar Overlays
    private Drawable allyMarker;
    private OverlayItem allyOverlay;
    private OverlayManager radarOverlayManager;
    private GeoPoint allyPoint;
	
	// UI
    private TextView scoreValue, timerValue;
    private ImageButton btnPower1, btnPower2;
    private PowerManager.WakeLock wl; 
    	
	 /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(
        WindowManager.LayoutParams.FLAG_FULLSCREEN,
        WindowManager.LayoutParams.FLAG_FULLSCREEN);
        
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);  
        wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "DoNotDimScreen"); 
        
        // creates the activity
        setContentView(R.layout.locate);
        
        registerViews();
        setupOnClickListeners();
        
        loadPrefs();
        setUpContainers();
       
	    mapOverlays = mapView.getOverlays();
	    mapOverlaysAllays = mapView.getOverlays();   
	    
	    posmarker = this.getResources().getDrawable(R.drawable.dotblue);
	    itemizedoverlay = new OverlayManager(posmarker);
	    
	    allyMarker = this.getResources().getDrawable(R.drawable.dotgreen);
	    radarOverlayManager = new OverlayManager(allyMarker);
	    
        if(host) {
            // if you created the game
            // center the map on your first position and update 
            // the center values on the database

            if(latDoubleValue!=0 && lonDoubleValue!=0) {
                // if we already have a clear position
                // set the center position of the game
                if(!centerIsSet) {
                    
                    Connection.setCenterPosition(idgame, latDoubleValue.intValue(), lonDoubleValue.intValue());
                    
                    Log.d("CENTER LAT", latDoubleValue+"");
                    Log.d("CENTER LON", lonDoubleValue+"");
                
                }
                
                Connection.setPosition(gameSessionID, latDoubleValue.intValue(), lonDoubleValue.intValue());
                
                point = new GeoPoint(latDoubleValue.intValue(), lonDoubleValue.intValue());
                
                mapView.setSatellite(true);
                mapView.getController().setCenter(point);
                mapView.setStreetView(false);
                mapView.setTraffic(false);
                mapView.getController().setZoom(18);
                mapView.getController().stopPanning();
                mapView.setClickable(false);
            
                // Add the point to the mapview
                playerOverlayItem = new OverlayItem(point, "", "");
                itemizedoverlay.addOverlay(playerOverlayItem);
                mapOverlays.add(itemizedoverlay);

                mapView.postInvalidate();
                
            } else {
                
                // otherwise set the variable for setting it 
                // at the first clear location we have
                centerIsSet = false;
            
            }
                    
        } else {
            // client
            if(myLat!=0 && myLon!=0) {
                
                if(mapOverlays.size() != 0) {
                    itemizedoverlay.removeOverlay(playerOverlayItem);
                    mapOverlays.remove(itemizedoverlay);
                }
                
                point = new GeoPoint(myLat.intValue(), myLon.intValue());
                // Add the point to the mapview
                playerOverlayItem = new OverlayItem(point, "", "");
                itemizedoverlay.addOverlay(playerOverlayItem);
                mapOverlays.add(itemizedoverlay);
    
                mapView.setSatellite(true);
                mapView.getController().setCenter(point);
                mapView.setStreetView(false);
                mapView.setTraffic(false);
                mapView.getController().setZoom(18);
                mapView.getController().stopPanning();
                mapView.setClickable(false);
                
                mapView.postInvalidate();
            }
            
        }

    }

	private void loadPrefs() {
        
        preferences = getSharedPreferences(PREF_FILE, MODE_PRIVATE);
        
        gameSessionID = preferences.getInt("gameSessionID", -1);
        idgame        = preferences.getInt("idgame", -1);
        host          = preferences.getBoolean("hostPlayer", false);
        centerIsSet   = preferences.getBoolean("centerIsSet", false);

        if(host){
        	lonDoubleValue = (double) preferences.getInt("lonDoubleValuePref", 0);
            latDoubleValue = (double) preferences.getInt("latDoubleValuePref", 0);
        } else {
            myLat = (double) preferences.getInt("latDoubleValue", 0);
            myLon = (double) preferences.getInt("lonDoubleValue", 0);
        }

    }
	
	public void reloadMyValues() {
        myLat = (double) preferences.getInt("latDoubleValue", 0);
        myLon = (double) preferences.getInt("lonDoubleValue", 0);
	}

	private void setUpContainers() {

	    mapView    = (MapView)  findViewById(R.id.mapview);
	    scoreValue = (TextView) findViewById(R.id.score_value);
	    timerValue = (TextView) findViewById(R.id.timer_value);
		
	}

	private void locateMe() {

	    // Acquire a reference to the system Location Manager
	    locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

	    Log.d("LOCATEME", " CALLED *************************************************");
	    
	    // Define a listener that responds to location updates
	    locationListener = new LocationListener() {
	        
	        public void onLocationChanged(Location location) {

	            if( isBetterLocation(location, bestLocation) ) {

	                // if the new location is the most accurate
	                // set it as the current best location
	                bestLocation = location;

	                latDoubleValue = location.getLatitude();
	                lonDoubleValue = location.getLongitude();

	                if (latDoubleValue != 0 && lonDoubleValue != 0) {

	                    // Called when a new location is found by the GPS location
	                    // provider update the lat and lon local values
	                    latDoubleValue = location.getLatitude() * 1E6;
	                    lonDoubleValue = location.getLongitude() * 1E6;

	                    point = new GeoPoint(latDoubleValue.intValue(), lonDoubleValue.intValue());

	                    if(mapOverlays.size() != 0) {
	                        itemizedoverlay.removeOverlay(playerOverlayItem);
	                        mapOverlays.remove(itemizedoverlay);
	                    }

	                    // Add the point to the mapview
	                    playerOverlayItem = new OverlayItem(point, "", "");
	                    itemizedoverlay.addOverlay(playerOverlayItem);
	                    mapOverlays.add(itemizedoverlay);

	                    mapView.postInvalidate();

	                    updateServerPosition();

	                    if (host) {
	                        if (!centerIsSet) {
	                            // if we already have a clear position
	                            // set the center position of the game

	                            int temp = Connection.setCenterPosition(idgame,
	                                    latDoubleValue.intValue(),
	                                    lonDoubleValue.intValue());

	                            point = new GeoPoint(
	                                    latDoubleValue.intValue(),
	                                    lonDoubleValue.intValue());

	                            Log.d("CENTER LAT", latDoubleValue+"");
	                            Log.d("CENTER LON", lonDoubleValue+"");

	                            mapView.setSatellite(true);
	                            mapView.getController().setCenter(point);
	                            mapView.setStreetView(false);
	                            mapView.setTraffic(false);
	                            mapView.getController().setZoom(18);
	                            mapView.getController().stopPanning();
	                            mapView.setClickable(false);

	                            if (temp != -1)
	                                centerIsSet = true;
	                            else
	                                centerIsSet = false;
	                        }
	                    } else {

	                        // client player
	                        
	                        if (!centerIsSet) {

	                            // if this player is not the host
	                            // and the center of the map
	                            // wasn't already set
	                            // set it and center the map

	                            String centerPos = Connection.getCenterPosition(idgame);

	                            if (centerPos.equalsIgnoreCase("EMPTY")) {
	                                // ERROR
	                                Utils.showToastShort(getBaseContext(), "CENTER POSITION ERROR");
	                            } else {

	                                String[] centerPosArray = centerPos.split("\\|");
	                                Double centerLat = Double.parseDouble(centerPosArray[0]);
	                                Double centerLon = Double.parseDouble(centerPosArray[1]);

	                                GeoPoint centerPoint = new GeoPoint( centerLat.intValue(), centerLon.intValue() );

	                                mapView.setSatellite(true);
	                                mapView.getController().setCenter(centerPoint);
	                                mapView.setStreetView(false);
	                                mapView.setTraffic(false);

	                                Log.d("MAX ZOOM LEVEL", mapView.getMaxZoomLevel()+"");

	                                if(18 > mapView.getMaxZoomLevel() )
	                                    mapView.getController().setZoom(mapView.getMaxZoomLevel());
	                                else
	                                    mapView.getController().setZoom(18);

	                                mapView.getController().stopPanning();
	                                mapView.setClickable(false);

	                                centerIsSet = true;

	                            }

	                        }

	                    }

	                }

	            }

	        }

            public void onStatusChanged(String provider, int status,
                    Bundle extras) {
            }

            public void onProviderEnabled(String provider) {

            }

            public void onProviderDisabled(String provider) {
            }

            public void updateServerPosition() {

                Connection.setPosition(gameSessionID, latDoubleValue.intValue(), lonDoubleValue.intValue());
            }

        };

        // Register the listener with the Location Manager to receive location
        // updates from the GPS and the cell towers
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 0, locationListener);
        //locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);

    }

	
	@Override
	protected boolean isRouteDisplayed() {
		// do not visualize routing information
		return false;
	}
	
	// because of android weird location system
	// the newer location is not always the best
	// so I included some basic logic to check
	// which one is the most accurate location
	protected boolean isBetterLocation(Location location, Location currentBestLocation) {
	    if (currentBestLocation == null) {
	        // A new location is always better than no location
	        return true;
	    }

	    // Check whether the new location fix is newer or older
	    long timeDelta = location.getTime() - currentBestLocation.getTime();
	    boolean isSignificantlyNewer = timeDelta > NEWER_CHECK;
	    boolean isSignificantlyOlder = timeDelta < -NEWER_CHECK;
	    boolean isNewer = timeDelta > 0;

	    // If it's been more than NEWER_CHECK since the current location, use the new location
	    // because the user has likely moved
	    if (isSignificantlyNewer) {
	        return true;
	    // If the new location is more than NEWER_CHECK older, it must be worse
	    } else if (isSignificantlyOlder) {
	        return false;
	    }

	    // Check whether the new location fix is more or less accurate
	    int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
	    boolean isLessAccurate = accuracyDelta > 0;
	    boolean isMoreAccurate = accuracyDelta < 0;
	    boolean isSignificantlyLessAccurate = accuracyDelta > 200;

	    // Check if the old and new location are from the same provider
	    boolean isFromSameProvider = isSameProvider(location.getProvider(),
	            currentBestLocation.getProvider());

	    // Determine location quality using a combination of timeliness and accuracy
	    if (isMoreAccurate) {
	        return true;
	    } else if (isNewer && !isLessAccurate) {
	        return true;
	    } else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
	        return true;
	    }
	    return false;
	}
	
	public void onResume() {
        
        wl.acquire();

        switch(Connection.getGamePhase(idgame)) {
        // before all players join, wait players

        case Utils.CREATED:
            Log.d("LOC. GAME PHASE", "Game created");
            
            startActivity(new Intent(getBaseContext(), WaitPlayersDialog.class));
            break;
            
        case Utils.WAITING_PLAYERS: 
        	Log.d("LOC. GAME PHASE", "Waiting for players");

        	startActivity(new Intent(getBaseContext(), WaitPlayersDialog.class));
            break;
        
        case Utils.SPREAD: 
            Log.d("LOC. GAME PHASE", "Spread players");
            
            reloadMyValues();
            if(!host && myLat!=0 && myLon!=0) {
  
                if(mapOverlays.size() != 0) {
                    itemizedoverlay.removeOverlay(playerOverlayItem);
                    mapOverlays.remove(itemizedoverlay);
                }
                
                point = new GeoPoint(myLat.intValue(), myLon.intValue());
                // Add the point to the mapview
                playerOverlayItem = new OverlayItem(point, "", "");
                itemizedoverlay.addOverlay(playerOverlayItem);
                mapOverlays.add(itemizedoverlay);
    
                mapView.postInvalidate();

            }
            
            startActivity(new Intent(getBaseContext(), SpreadTimer.class));
            break;
        
        case Utils.STARTED: 
            Log.d("LOC. GAME PHASE", "Teams assigned");

            if (Connection.getTeam(gameSessionID) == 0){
            	
                Connection.setPlayerState(gameSessionID, Utils.H_NO_POWER);
            	Connection.setCaptureState(gameSessionID, Utils.H_NO_CAPTURE);
            	captureTimer = 0;
            	oldPlayerState = -1;
            	oldCaptureState = -1;
            	
            	// if you are an human
            	// change the UI
            	
            	findViewById(R.id.externalFrame).setBackgroundResource(R.drawable.humanframe);
            	btnPower1.setImageResource(R.drawable.pbtnhumanradar);
            	btnPower1.setBackgroundResource(R.drawable.humanbtndef);
            	
            	btnPower2.setImageResource(R.drawable.pbtnhumanjammer);
            	btnPower2.setBackgroundResource(R.drawable.humanbtndef);
            	
            } else {
                
            	Connection.setPlayerState(gameSessionID, Utils.A_NO_POWER);
            	Connection.setCaptureState(gameSessionID, Utils.A_NO_CAPTURE);
            	captureTimer = 0;
            	oldCaptureState = -1;
            	oldPlayerState = -1;
            
            }
                
            refreshing = true;
            //refreshPlayerStateThread();
            
            allServerThread();
            
            findViewById(R.id.commonLoadingBG).setVisibility(4);
            
            break;
        	
        }
        
        locateMe();
        
        super.onResume();
		
	}

	// Checks whether two providers are the same 
	private boolean isSameProvider(String provider1, String provider2) {
	    if (provider1 == null) {
	      return provider2 == null;
	    }
	    return provider1.equals(provider2);
	}

	public void onPause() {
		// Remove the listener you previously added
		locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
		locationManager.removeUpdates(locationListener);
		
		if(refreshing) {
		    // not in the first time
		    stopRefreshing();
		    wl.release(); 
		}
			
					
		super.onPause();
	}
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	super.onCreateOptionsMenu(menu);
    	MenuInflater inflater = getMenuInflater();
    	inflater.inflate(R.layout.settingsmenu, menu);
    	return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	switch(item.getItemId()) {
    	case R.id.settings:
    		startActivity(new Intent(this, Preferences.class));
    		
    		return true;
    	}
    return false;
    }

	@Override
	public void onClick(View v) {

    	switch(v.getId()) {
    	
	    	case R.id.power_button_left:
    		

	    		Utils.showTopToastShort(getBaseContext(), "With the Radar you can see where\nyour team mates are on the map.\nLongpress to activate!");	
	    		
	    		//TO-DO load a new power right after this one is finished
	    		
	    		break;
	    		
	    	case R.id.power_button_right:

	    		
	    	    if(playerTeam == 0)
	    	        Utils.showTopToastShort(getBaseContext(), "Jam the closest an alien and\ndon't be captured!\nLongpress to activate!");
	    	    else
	    	        Utils.showTopToastShort(getBaseContext(), "Unjam yourself!\nLongpress to activate!");
	    		
	    		
	    		//TO-DO load a new power right after this one is finished
	    		
	    		break;
		
    	}

    }
	
	
    private void setupOnClickListeners() {
    	
        btnPower1.setOnClickListener(this);
    	btnPower2.setOnClickListener(this);

    	btnPower1.setOnLongClickListener(this);
    	btnPower2.setOnLongClickListener(this);

	}

	private void registerViews() {
		btnPower1 = (ImageButton) this.findViewById(R.id.power_button_left);
		btnPower2 = (ImageButton) this.findViewById(R.id.power_button_right);
	}
	
	// RADAR POWER
	private void powerRadar(int team) {

		// runs only once
		enterPlayerState = false;
		exitPlayerState = false;
		
		String allPositionsString = Connection.retrieveTeamMatesPositions(idgame, gameSessionID, team);
		
		String[] positions = allPositionsString.split("\\|");
		int numberOfTeamMates = positions.length / 2;
		
		
		
		if(numberOfTeamMates == 0) {
		    
		    // no team mates to show
//		    Utils.showToastShort(getBaseContext(), "No team mates to show");
			updateThreadHandler.sendEmptyMessage(Utils.MSG_B_RADAR_NOT);
		    radarTimer = 1;
		    
		} else {
		
		    radarTimer = 8;
		    
    		// HUMAN RADAR
    		if (team == 0){
    			
    		    for(int i=0; i<numberOfTeamMates*2; i+=2) {
    		        
    		        allyPoint = new GeoPoint(Integer.parseInt(positions[i]), Integer.parseInt(positions[i+1]));

    		        updateThreadHandler.sendEmptyMessage(Utils.UPDATE_UI_RADAR_1);
    		    }

    		}
    		// ALIEN RADAR
    		else {
    			
                for(int i=0; i<numberOfTeamMates*2; i+=2) {
                    
                    allyPoint = new GeoPoint(Integer.parseInt(positions[i]), Integer.parseInt(positions[i+1]));

                    updateThreadHandler.sendEmptyMessage(Utils.UPDATE_UI_RADAR_1);

                    
                }
    		}
    		
    		updateThreadHandler.sendEmptyMessage(Utils.UPDATE_UI_RADAR_2);
    		
		}
	}
	
	// JAMMER POWER
	private void jammer() {

	    // runs only once
	    enterPlayerState = false;
	    exitPlayerState = false;
	    
	    updateThreadHandler.sendEmptyMessage(Utils.UPDATE_UI_JAM_ON);
	    
	    jammerTimer = 7;

	}
	

    public void stopRefreshing(){	
       refreshing = false;
	   
    }
    
    private void updateScoreAndTimer() {
        
    	matchScore = Connection.getNumberOfEnemies(idgame, playerTeam);
    	matchTime = Connection.getRemainingTime(idgame);
    	
    	updateThreadHandler.sendEmptyMessage(Utils.UPDATE_SCORE_TIME);
    	
        
        
    }
    
    private void cleanOverlays () {
    	
    	switch(oldPlayerState) {
    	
	    	case Utils.A_RADAR :
	    		
	    		// cleans the alien ui overlays
	    	    radarOverlayManager.removeOverlay(allyOverlay);
                mapOverlaysAllays.remove(radarOverlayManager);
	    		mapView.postInvalidate();
	    		
	    		break;
	    		
	    	case Utils.H_RADAR :
	    		
                // cleans the human ui overlays
                radarOverlayManager.removeOverlay(allyOverlay);
                mapOverlaysAllays.remove(radarOverlayManager);
                mapView.postInvalidate();
	    		
	    		break;
    	
    	}
    	
    }
    
    private void updateCaptureState() {
    	
    	
    	//Log.d("OLD PS - BEFORE UP", oldPlayerState+"");
    	// stores previous game state
    	if(oldCaptureState != captureState){
    		oldCaptureState = captureState;
    	    Log.d("OLD CS CHANGED", oldCaptureState+"");
    	}

    	Log.d("CS - BEFORE UP", captureState+"");
    	captureState = Connection.getCaptureState(gameSessionID);
    	Log.d("CS - AFTER UP", captureState+"");
    	
    	// get the player team
    	playerTeam = Connection.getTeam(gameSessionID);  	
    		
		switch(captureState){
		
			// =================================================
	    	// CAPTURING if player is HUMAN
	    	// =================================================
		
			// is not being captured
			case Utils.H_NO_CAPTURE:
				captureTimer = 0;
				break;
				
			case Utils.H_BEING_CAPTURED:
//				Utils.showToastShort(getBaseContext(), "YOU ARE BEING CAPTURED!" );
				updateThreadHandler.sendEmptyMessage(Utils.MSG_H_CAPTURING);
				captureTimer++;
				
				if(captureTimer > 3){
					Connection.setCaptureState(gameSessionID, Utils.H_JUST_CAPTURED);
				}
				break;
				
			// just captured
			case Utils.H_JUST_CAPTURED:
//				Utils.showToastShort(getBaseContext(), "YOU WERE CAPTURED!\nYou are an alien now, catch other humans!" );
				updateThreadHandler.sendEmptyMessage(Utils.MSG_H_CAPTURED);
				Connection.assignTeam(gameSessionID, 1);
				Connection.setCaptureState(gameSessionID, Utils.A_NO_CAPTURE);
				Connection.setPlayerState(gameSessionID, Utils.A_NO_POWER);
				
				
				updateThreadHandler.sendEmptyMessage(Utils.UPDATE_UI_JUST_CAPTURED);
				

				
				captureTimer = 0;
				break;
				
			// just escaped capture
			case Utils.H_JUST_ESCAPED:
//				Utils.showToastShort(getBaseContext(), "YOU JUST ESCAPED!" );
				updateThreadHandler.sendEmptyMessage(Utils.MSG_H_ESCAPED);
				Connection.setCaptureState(gameSessionID, Utils.H_NO_CAPTURE);
				
				captureTimer = 0;
				break;
		
			// =================================================
			// CAPTURING if player is ALIEN
			// =================================================
		
			// is not capturing
			case Utils.A_NO_CAPTURE:
				
				captureTimer = 0;
				
				break;
				
			// is capturing
			case Utils.A_CAPTURING:
//				Utils.showToastShort(getBaseContext(), "YOU ARE CAPTURING A HUMAN!" );
				updateThreadHandler.sendEmptyMessage(Utils.MSG_A_CAPTURING);
				captureTimer++;
				
				if(captureTimer > 3){
					Connection.setCaptureState(gameSessionID, Utils.A_JUST_CAPTURED);
					updateThreadHandler.sendEmptyMessage(Utils.MSG_A_CAPTURED);
				}
				
				break;
				
			// just captured
			case Utils.A_JUST_CAPTURED:
				

				Connection.setCaptureState(gameSessionID, Utils.A_NO_CAPTURE);
				
				captureTimer = 0;
				break;
				
			// just escaped capture
			case Utils.A_JUST_ESCAPED:
				
				updateThreadHandler.sendEmptyMessage(Utils.MSG_A_ESCAPED);
				Connection.setCaptureState(gameSessionID, Utils.A_NO_CAPTURE);
				
				captureTimer = 0;
				break;
				
		}

    }
    
	private void updatePlayerState () {
	
	//		This function will be called every interval, to update 
	//		the player state according to its state on the server.
	
		//Log.d("OLD PS - BEFORE UP", oldPlayerState+"");
		// stores previous game state
		if(oldPlayerState != playerState){
		    oldPlayerState = playerState;
		    exitPlayerState = true;
		    Log.d("OLD PS CHANGED", oldPlayerState+"");
		}
	
		Log.d("PS - BEFORE UP", playerState+"");
		playerState = Connection.getPlayerState(gameSessionID);
		Log.d("PS - AFTER UP", playerState+"");
		
		// get the player team
		playerTeam = Connection.getTeam(gameSessionID);
		
		switch(playerState) {
		
			//=================================
			// ALIEN POOOOOOWEEEERS!!!!!!! 
			//=================================
		
			case Utils.A_NO_POWER:
				
				if (exitPlayerState) { 
					
					updateThreadHandler.sendEmptyMessage(Utils.UPDATE_CLEAN_OVERLAYS);
					
					// it will be the first run for the next power
					enterPlayerState = true;
					exitPlayerState = false;
					
					updateThreadHandler.sendEmptyMessage(Utils.UPDATE_LBTN_STATE_ON);
					updateThreadHandler.sendEmptyMessage(Utils.UPDATE_RBTN_STATE_ON);
					
				}
					
				break;
			
			case Utils.A_RADAR:

				if (enterPlayerState)
					powerRadar(playerTeam);
				
				radarTimer--;
				
				if (radarTimer == 0){
					enterPlayerState = false;				
					exitPlayerState = true;
					Connection.setPlayerState(gameSessionID, Utils.A_NO_POWER);
				}
				
				break;
				
            case Utils.A_JAMMED:
                                
                if (enterPlayerState){
                	jammer();
                	updateThreadHandler.sendEmptyMessage(Utils.UPDATE_LBTN_STATE_OFF);
                	updateThreadHandler.sendEmptyMessage(Utils.UPDATE_RBTN_STATE_ON);
                }
                
                jammerTimer--;
                
                if (jammerTimer == 0){
                    enterPlayerState = false;               
                    exitPlayerState = true;
                    
                    updateThreadHandler.sendEmptyMessage(Utils.UPDATE_UI_JAM_OFF);
                    Connection.setPlayerState(gameSessionID, Utils.A_NO_POWER);
                }
                
                break;
                
            case Utils.A_JAMMER_SHIELD:
                
            	updateThreadHandler.sendEmptyMessage(Utils.UPDATE_UI_JAM_OFF);
                Connection.setPlayerState(gameSessionID, Utils.A_NO_POWER);
                
                break;
				
			case Utils.A_END_GAME:
				
				stopRefreshing();
				// start aliens win activity
				
				
				
				startActivity(new Intent(getBaseContext(), WinGameAlien.class));
				
				break;
				
			//=================================
			// NOW HUMAN POOOOOOWEEEERS!!!!!!! 
			//=================================
				
			case Utils.H_NO_POWER:
				
				if (exitPlayerState) { 
					
					updateThreadHandler.sendEmptyMessage(Utils.UPDATE_CLEAN_OVERLAYS);
					
					// it will be the first run for the next power
					enterPlayerState = true;
					exitPlayerState = false;
					
					updateThreadHandler.sendEmptyMessage(Utils.UPDATE_LBTN_STATE_ON);
					updateThreadHandler.sendEmptyMessage(Utils.UPDATE_RBTN_STATE_ON);
					
				}
				
				break;
				
			case Utils.H_RADAR:
								
				if (enterPlayerState)
					powerRadar(playerTeam);
				
				radarTimer--;
				
				if (radarTimer == 0){
					enterPlayerState = false;				
					exitPlayerState = true;
					Connection.setPlayerState(gameSessionID, Utils.H_NO_POWER);
				}
				break;
				
			case Utils.H_JAMMER:
                
                if (enterPlayerState){
                    // get the closest enemy
                    int gameSessionToJam = Connection.getClosestEnemy(idgame, gameSessionID, 0);
                    // and jam him if you can
                    if(Connection.getPlayerState(gameSessionToJam) != Utils.A_JAMMER_SHIELD) {
                    	
                    	updateThreadHandler.sendEmptyMessage(Utils.MSG_H_JAMMER);
                        
                        Connection.setPlayerState(gameSessionToJam, Utils.A_JAMMED);
                    
                    } else {
//                        Utils.showToastShort(getBaseContext(), "You can't jam the closest alien,\n It has the anti-jam mojo!");
                    	updateThreadHandler.sendEmptyMessage(Utils.MSG_H_JAMMER_NOT);
                    }
                    
                    enterPlayerState = false;
                    Connection.setPlayerState(gameSessionID, Utils.H_NO_POWER);
                }
                

			    break;
				
			case Utils.H_END_GAME:
				
				stopRefreshing();
				// start aliens win activity
				
				if(playerTeam == 1)
					startActivity(new Intent(getBaseContext(), LoseGameAlien.class));
				else
					startActivity(new Intent(getBaseContext(), WinGameHuman.class));
				
				
				break;
		}	
		
		// =================================================
		// controls the buttons (only one power at a time now)
		// =================================================
//		if (isSomePowerActive) {
//			btnPower1.setEnabled(false);
//			btnPower2.setEnabled(false);
//		} 
//		else {
//			btnPower1.setEnabled(true);
//			btnPower2.setEnabled(true);
//		}	
	}

	@Override
	public boolean onLongClick(View v) {
		
		switch(v.getId()) {
    	
    	case R.id.power_button_left:

    		enterPlayerState = true;
    		
    		Utils.showToastShort(getBaseContext(), "ACTIVATING RADAR");
    		
    		if(playerTeam == 0)
    			Connection.setPlayerState(gameSessionID, Utils.H_RADAR);
    		else
    			Connection.setPlayerState(gameSessionID, Utils.A_RADAR);
    		
    		exitPlayerState = true;
    		
    		btnPower1.setPressed(false);
    		btnPower1.setEnabled(false);
    		
			btnPower2.setPressed(false);
    		btnPower2.setEnabled(false);			
    		
    		
    		
    		
    		return true;
    		
//    		break;
    		
    	case R.id.power_button_right:

            if(playerTeam == 0){

                enterPlayerState = true;
                Utils.showToastShort(getBaseContext(), "ACTIVATING JAMMER");
                Connection.setPlayerState(gameSessionID, Utils.H_JAMMER);
                
                
                
            } else {

                if(playerState == Utils.A_JAMMED) {
                    // the player is being jammed
                    // activate the anti-jammer
                    Utils.showToastShort(getBaseContext(), "ACTIVATING ANTI-JAMMER");
                    Connection.setPlayerState(gameSessionID, Utils.A_JAMMER_SHIELD);
                    exitPlayerState = true;
                } else {
                	Utils.showToastShort(getBaseContext(), "You can't use the anti-jammer without being jammed");
                	exitPlayerState = true;
                }
                
                if(playerState == Utils.H_JAMMER) {
                	Utils.showToastShort(getBaseContext(), "ACTIVATING JAMMER");
                }
                    

            }
            
            btnPower1.setPressed(false);
    		btnPower1.setEnabled(false);
            
            btnPower2.setPressed(false);
            btnPower2.setEnabled(false);

    		return true;
    		
//    		break;
	
		}
		
		
		return false;
	}
	
    public void allServerThread() {
        if (!pollingstart) {
            pollingstart = true;
            new Thread(new Runnable() {
                public void run() {

                    Looper.prepare();

                    while (refreshing) {

                        updateCaptureState();
                        updatePlayerState();
                        updateScoreAndTimer();

                        try {
                            Thread.sleep(2000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                    }

                }
            }).start();
        }
    }
	
	private final Handler updateThreadHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			
			
			switch(msg.what){
			
			
				case Utils.UPDATE_SCORE_TIME:
					
					scoreValue.setText(""+matchScore);
			        timerValue.setText(""+matchTime);
			        break;
			        
				case Utils.UPDATE_RBTN_STATE_ON:
					
					// Enabled and not pressed
					btnPower2.setEnabled(true);
					btnPower2.setPressed(false);
			        break;
			        
				case Utils.UPDATE_RBTN_STATE_OFF:
					
					// Disabled and not pressed
					btnPower2.setEnabled(false);
					btnPower2.setPressed(false);
			        break;
			        
				case Utils.UPDATE_LBTN_STATE_ON:
					
					// Enabled and not pressed
					btnPower1.setEnabled(true);
					btnPower1.setPressed(false);
			        break;
			        
				case Utils.UPDATE_LBTN_STATE_OFF:
					
					// Disabled and not pressed
					btnPower1.setEnabled(false);
					btnPower1.setPressed(false);
			        break;
			        
				case Utils.UPDATE_CLEAN_OVERLAYS:
					
					// Disabled and not pressed
					cleanOverlays();
			        break;
			        
				case Utils.UPDATE_UI_JAM_OFF:
					
					findViewById(R.id.beingJammedScreen).setVisibility(4);
					
					break;
					
				case Utils.UPDATE_UI_JAM_ON:
					
					findViewById(R.id.beingJammedScreen).setVisibility(0);
					
					break;
					
				case Utils.UPDATE_UI_RADAR_1:
					
					// draws human team mates
    		        allyOverlay = new OverlayItem(allyPoint, "", "");
    		        radarOverlayManager.addOverlay(allyOverlay);
                    mapOverlaysAllays.add(radarOverlayManager);
                    
                    break;
                    
				case Utils.UPDATE_UI_RADAR_2:
					
					mapView.postInvalidate();
					
					break;
					
				case Utils.UPDATE_UI_JUST_CAPTURED:
					
					findViewById(R.id.externalFrame).setBackgroundResource(R.drawable.alienframe);
	            	btnPower1.setImageResource(R.drawable.pbtnalienradar);
	            	btnPower1.setBackgroundResource(R.drawable.alienbtndef);
	            	
	            	btnPower2.setImageResource(R.drawable.pbtnalienantijammer);
	            	btnPower2.setBackgroundResource(R.drawable.alienbtndef);
					
					break;
					
				case Utils.MSG_H_CAPTURING:
					Utils.showToastShort(getBaseContext(), "YOU ARE BEING CAPTURED!" );
					break;
					
				case Utils.MSG_H_CAPTURED:
					Utils.showToastShort(getBaseContext(), "YOU WERE CAPTURED!\nYou are an alien now, catch other humans!" );					
					break;
					
				case Utils.MSG_H_ESCAPED:
					Utils.showToastShort(getBaseContext(), "YOU JUST ESCAPED!" );
					break;
					
				case Utils.MSG_A_CAPTURING:
					Utils.showToastShort(getBaseContext(), "YOU ARE CAPTURING A HUMAN!" );
					break;
					
				case Utils.MSG_A_CAPTURED:
					Utils.showToastShort(getBaseContext(), "YEAH! YOU JUST CAPTURED IT!" );					
					break;
					
				case Utils.MSG_A_ESCAPED:
					Utils.showToastShort(getBaseContext(), "THE HUMAN JUST ESCAPED!" );
					break;
					
				case Utils.MSG_H_JAMMER:
					Utils.showToastShort(getBaseContext(), "The closest alien is being jammed!");
					break;
					
				case Utils.MSG_H_JAMMER_NOT:
					Utils.showToastShort(getBaseContext(), "You can't jam the closest alien,\n It has the anti-jam mojo!");
					break;
					
				case Utils.MSG_B_RADAR_NOT:
					Utils.showToastShort(getBaseContext(), "No team mates to show");
					break;
					
		        
			}
			
			
		}
	};
	
}
